from PyQt4 import Qt
from gnuradio import gr
from gnuradio.qtgui import qtgui
from gnuradio.gr import firdes

## TODO: Create Option Parser

class gui(Qt.QWidget):
	def __init__(self, window_name, args, tb):
		self.qapp = Qt.QApplication(args)
		Qt.QWidget.__init__(self)
		self.setWindowTitle(window_name)
		self.top_scroll_layout = Qt.QVBoxLayout()
		self.setLayout(self.top_scroll_layout)
		self.top_scroll = Qt.QScrollArea()
		self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
		self.top_scroll_layout.addWidget(self.top_scroll)
		self.top_scroll.setWidgetResizable(True)
		self.top_widget = Qt.QWidget()
		self.top_scroll.setWidget(self.top_widget)
		self.top_layout = Qt.QVBoxLayout(self.top_widget)
		self.top_grid_layout = Qt.QGridLayout()
		self.top_layout.addLayout(self.top_grid_layout)

		self.enable_gui = tb.enable_gui
		self.tb = tb

	def create_tab_widget(self, tab_names, upper_layout, return_layouts):
		tab_widget = Qt.QTabWidget()
		for i in tab_names:
			if type(i) == list:
				#print 'Creating Tab', i[0]
				tab_layout = self.create_tab(tab_widget, i[0])
				#print 'Creating down widget', i[1:]
				self.create_tab_widget(i[1:], tab_layout, return_layouts)
			else:
				#print 'Creating Tab', i
				tab_layout = self.create_tab(tab_widget, i)
				return_layouts += [tab_layout]
		upper_layout.addWidget(tab_widget)
		return return_layouts

	def create_time_sink_vf(self, samp_rate, vec_block, vec_tab_names):
		connect_blocks = []
		gui_sink = []
		for i in range(len(vec_tab_names)):
			connect_blocks += [vec_block[i]]
			gui_sink += [self.create_time_sink_f(samp_rate, vec_tab_names[i])]
		return [connect_blocks, gui_sink]

	def create_time_sink_f(self, samp_rate, tab_name):
		gui_sink =  qtgui.time_sink_f(1024, samp_rate, tab_name,1)
		return [gui_sink, gui_sink]

	def create_gui_sink_bf(self, samp_rate, plot_name):
		char2float = gr.char_to_float()
		gui_sink = qtgui.sink_f( 512, firdes.WIN_BLACKMAN_hARRIS, 0, samp_rate, plot_name, False, False, True, False)
		if self.enable_gui:
			self.tb.connect(char2float, gui_sink)
		return [char2float, gui_sink]

	def create_gui_sink_cc(self, samp_rate, plot_name):
		gui_sink = qtgui.sink_c( 512, firdes.WIN_BLACKMAN_hARRIS, 0, samp_rate, plot_name, True, False, True, True)
		return [gui_sink, gui_sink]

	def get_top_layout(self):
		return self.top_layout

	def create_tab(self, upper, tab_name):
		widget = Qt.QWidget()
		layout = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom, widget)
		grid_layout = Qt.QGridLayout()
		layout.addLayout(grid_layout)
		upper.addTab(widget, tab_name)
		return layout

	def start(self):
		self.show()
		self.qapp.exec_()
